﻿using FineUIPro;
using KPI_SYSTEM.Code;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace KPI_SYSTEM.SalaryPage
{
    public partial class SalaryTotal : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadBaseData();
                BindData();
            }
            PublicMethod.GetApprovalButton("SalaryTotal.aspx", Toolbar2, GridSalary);
            PublicMethod.GetApprovalButton("SalaryTotal.aspx", Toolbar2, GridDeduct);
        }
        /// <summary>
        /// 加载页面必备数据
        /// </summary>
        private void LoadBaseData()
        {
            DataTable tableSalaryItem = SqlHelper.ExecuteDataset(CommandType.Text, @"SELECT REC_ID,(SALARY_ITEM_NAME+'(编号：'+SALARY_ITEM_CODE+')') AS ITEM_NAME FROM HOS_SALARY_ITEM WHERE SALARY_ITEM_TYPE=1 ORDER BY SALARY_ITEM_SEQ").Tables[0];
            chlFormSALARY_ITEMS.DataTextField = "ITEM_NAME";
            chlFormSALARY_ITEMS.DataValueField = "REC_ID";
            chlFormSALARY_ITEMS.DataSource = tableSalaryItem;
            chlFormSALARY_ITEMS.DataBind();


            DataTable tableDeductItem = SqlHelper.ExecuteDataset(CommandType.Text, @"SELECT REC_ID,(SALARY_ITEM_NAME+'(编号：'+SALARY_ITEM_CODE+')') AS ITEM_NAME FROM HOS_SALARY_ITEM WHERE SALARY_ITEM_TYPE=0 ORDER BY SALARY_ITEM_SEQ").Tables[0];
            chlFormDEDUCT_ITEMS.DataTextField = "ITEM_NAME";
            chlFormDEDUCT_ITEMS.DataValueField = "REC_ID";
            chlFormDEDUCT_ITEMS.DataSource = tableDeductItem;
            chlFormDEDUCT_ITEMS.DataBind();

        }
        private void BindData()
        {
            StringBuilder sqlWhere = new StringBuilder();
            String mainDataSql = @"SELECT A.REC_ID,A.TOTAL_ITEM_NAME,A.TOTAL_ITEM_TYPE,A.TOTAL_ITEM_REMARK,A.CREATE_TIME,A.TOTAL_ITEM_CODE,A.TOTAL_ITEM_SEQ,
                                        CASE WHEN A.TOTAL_ITEM_TYPE=0 THEN '扣款合计项' WHEN A.TOTAL_ITEM_TYPE=1 THEN '发款合计项' END AS TOTAL_ITEM_TYPE_NAME,
                                        (SELECT USER_NAME FROM USER_DICT WHERE REC_ID=A.CREATE_USER) AS CREATE_USER_NAME
                                        FROM HOS_SALARY_TOTAL AS A WHERE 1=1 {0} ORDER BY A.TOTAL_ITEM_SEQ";
            if (tbxNameSerach.Text.Trim() != "")
            {
                sqlWhere.Append(" AND A.TOTAL_ITEM_NAME LIKE '%" + tbxNameSerach.Text.Trim() + "%'");
            }
            mainDataSql = string.Format(mainDataSql, sqlWhere.ToString());
            DataTable mainDataTable = SqlHelper.ExecuteDataset(CommandType.Text, mainDataSql).Tables[0];


            DataTable dtSalary = new DataTable();
            DataTable dtDeduct = new DataTable();
            dtSalary = mainDataTable.Clone();
            dtDeduct = mainDataTable.Clone();
            DataRow[] rowSalary = mainDataTable.Select("TOTAL_ITEM_TYPE=1");
            DataRow[] rowDeduct = mainDataTable.Select("TOTAL_ITEM_TYPE=0");
            foreach (DataRow row in rowSalary)  // 将查询的结果添加到dt中； 
            {
                dtSalary.Rows.Add(row.ItemArray);
            }
            foreach (DataRow row in rowDeduct)  // 将查询的结果添加到dt中； 
            {
                dtDeduct.Rows.Add(row.ItemArray);
            }
            GridSalary.DataSource = dtSalary;
            GridSalary.DataBind();
            GridDeduct.DataSource = dtDeduct;
            GridDeduct.DataBind();
        }
        // 根据行ID来删除行数据
        private void DeleteRowByID(int rowID, String itemCode)
        {
            try
            {
                SqlHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM HOS_SALARY_TOTAL WHERE REC_ID=" + rowID);
                SqlHelper.ExecuteNonQuery(CommandType.Text, "ALTER TABLE HOS_SALSRY_DETAIL DROP COLUMN [" + itemCode + "]");
                SqlHelper.ExecuteNonQuery(CommandType.Text, "ALTER TABLE HOS_SALSRY_DETAIL_BAK DROP COLUMN [" + itemCode + "]");
            }
            catch (Exception ex)
            {
                throw new Exception("删除失败！");
            }
        }
        protected void GridSalary_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int rowID = Convert.ToInt32(GridSalary.DataKeys[e.RowIndex][0]);
                try
                {
                    String itemCode = GridSalary.Rows[e.RowIndex].Values[2].ToString();
                    DeleteRowByID(rowID, itemCode);
                    BindData();
                    ShowNotify("删除数据成功!");

                }
                catch (Exception ex)
                {
                    ShowNotify("删除数据失败!");
                }
            }
        }
        protected void GridDeduct_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int rowID = Convert.ToInt32(GridDeduct.DataKeys[e.RowIndex][0]);
                try
                {
                    String itemCode = GridDeduct.Rows[e.RowIndex].Values[2].ToString();
                    DeleteRowByID(rowID, itemCode);
                    BindData();
                    ShowNotify("删除数据成功!");

                }
                catch (Exception ex)
                {
                    ShowNotify("删除数据失败!");
                }
            }
        }
        protected void GridSalary_PreRowDataBound(object sender, GridPreRowEventArgs e)
        {
            // 如果绑定到 DataTable，那么这里的 DataItem 就是 DataRowView
            DataRowView row = e.DataItem as DataRowView;
            int rowId = Convert.ToInt32(row["REC_ID"]);

            LinkButtonField editField = GridSalary.FindColumn("Edit") as LinkButtonField;
            editField.OnClientClick = String.Format("showEditSalaryWindow('{0}');", rowId);
        }
        protected void GridDeduct_PreRowDataBound(object sender, GridPreRowEventArgs e)
        {
            // 如果绑定到 DataTable，那么这里的 DataItem 就是 DataRowView
            DataRowView row = e.DataItem as DataRowView;
            int rowId = Convert.ToInt32(row["REC_ID"]);

            LinkButtonField editField = GridDeduct.FindColumn("Edit") as LinkButtonField;
            editField.OnClientClick = String.Format("showEditDeductWindow('{0}');", rowId);
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }
        protected void tbxFormTOTAL_ITEM_NAME_TextChanged(object sender, EventArgs e)
        {
            tbxFormTOTAL_ITEM_CODE.Text = PublicMethod.GetSpellCode(tbxFormTOTAL_ITEM_NAME.Text.Trim());
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                String strRowID = hfFormID.Text;
                String strOldName = hfFormTOTAL_ITEM_NAME.Text;
                String strOldCode = hfFormTOTAL_ITEM_CODE.Text;
                Dictionary<String, String> keyValuePairs = new Dictionary<string, string>();
                keyValuePairs.Clear();
                if (tbxFormTOTAL_ITEM_NAME.Text.Trim() != "")
                {
                    keyValuePairs.Add("TOTAL_ITEM_NAME", tbxFormTOTAL_ITEM_NAME.Text.Trim());
                }
                else
                {
                    ShowNotify("条目名不能为空!");
                    return;
                }
                if (tbxFormTOTAL_ITEM_CODE.Text.Trim() != "")
                {
                    keyValuePairs.Add("TOTAL_ITEM_CODE", tbxFormTOTAL_ITEM_CODE.Text.Trim());
                }
                else
                {
                    ShowNotify("条目编码不能为空!");
                    return;
                }
                if (String.Join(",", chlFormSALARY_ITEMS.SelectedValueArray) != "" || String.Join(",", chlFormDEDUCT_ITEMS.SelectedValueArray) != "")
                {
                    String itemIDs = String.Join(",", chlFormSALARY_ITEMS.SelectedValueArray) + "," + String.Join(",", chlFormDEDUCT_ITEMS.SelectedValueArray);
                    keyValuePairs.Add("TOTAL_ITEM_MAPPING", itemIDs.TrimEnd(',').TrimStart(','));
                }
                else
                {
                    ShowNotify("工资条项目不能为空!");
                    return;
                }
                if (tbxFormTOTAL_ITEM_SEQ.Text.Trim() != "")
                {
                    keyValuePairs.Add("TOTAL_ITEM_SEQ", tbxFormTOTAL_ITEM_SEQ.Text.Trim());
                }
                if (ddlFormTOTAL_ITEM_TYPE.SelectedValue != null && ddlFormTOTAL_ITEM_TYPE.SelectedValue != "")
                {
                    keyValuePairs.Add("TOTAL_ITEM_TYPE", ddlFormTOTAL_ITEM_TYPE.SelectedValue);
                }
                if (tbxFormTOTAL_ITEM_REMARK.Text.Trim() != "")
                {
                    keyValuePairs.Add("TOTAL_ITEM_REMARK", tbxFormTOTAL_ITEM_REMARK.Text.Trim());
                }
                if (String.IsNullOrEmpty(strRowID))
                {
                    Int32 checkName = (Int32)SqlHelper.ExecuteScalar(CommandType.Text, "SELECT COUNT(*) FROM HOS_SALARY_TOTAL WHERE TOTAL_ITEM_NAME='" + tbxFormTOTAL_ITEM_NAME.Text.Trim() + "'");
                    if (checkName > 0)
                    {
                        ShowNotify("条目名重复!");
                        return;
                    }
                    Int32 checkCode = (Int32)SqlHelper.ExecuteScalar(CommandType.Text, "SELECT COUNT(*) FROM HOS_SALARY_TOTAL WHERE TOTAL_ITEM_CODE='" + tbxFormTOTAL_ITEM_CODE.Text.Trim() + "'");
                    if (checkCode > 0)
                    {
                        ShowNotify("条目编码重复!");
                        return;
                    }
                    keyValuePairs.Add("CREATE_TIME", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    keyValuePairs.Add("CREATE_USER", Session["UserID"].ToString());
                    PublicMethod.SetDataMethod("SELECT * FROM HOS_SALARY_TOTAL WHERE 1=2", "Add", keyValuePairs);
                    SqlHelper.ExecuteNonQuery(CommandType.Text, "ALTER TABLE HOS_SALSRY_DETAIL ADD [" + tbxFormTOTAL_ITEM_CODE.Text.Trim() + "] NVARCHAR (20) NULL");
                    SqlHelper.ExecuteNonQuery(CommandType.Text, "ALTER TABLE HOS_SALSRY_DETAIL_BAK ADD [" + tbxFormTOTAL_ITEM_CODE.Text.Trim() + "] NVARCHAR (20) NULL");
                    ShowNotify("保存成功!");
                }
                else
                {
                    if (tbxFormTOTAL_ITEM_NAME.Text.Trim() != strOldName)
                    {
                        Int32 checkName = (Int32)SqlHelper.ExecuteScalar(CommandType.Text, "SELECT COUNT(*) FROM HOS_SALARY_TOTAL WHERE TOTAL_ITEM_NAME='" + tbxFormTOTAL_ITEM_NAME.Text.Trim() + "'");
                        if (checkName > 0)
                        {
                            ShowNotify("条目名重复!");
                            return;
                        }
                    }
                    if (tbxFormTOTAL_ITEM_CODE.Text.Trim() != strOldCode)
                    {
                        Int32 checkCode = (Int32)SqlHelper.ExecuteScalar(CommandType.Text, "SELECT COUNT(*) FROM HOS_SALARY_TOTAL WHERE TOTAL_ITEM_CODE='" + tbxFormTOTAL_ITEM_CODE.Text.Trim() + "'");
                        if (checkCode > 0)
                        {
                            ShowNotify("条目编码重复!");
                            return;
                        }
                    }
                    keyValuePairs.Add("REC_ID", strRowID);
                    keyValuePairs.Add("UPDATE_TIME", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    keyValuePairs.Add("UPDATE_USER", Session["UserID"].ToString());
                    PublicMethod.SetDataMethod("SELECT * FROM HOS_SALARY_TOTAL WHERE REC_ID=" + strRowID, "Update", keyValuePairs);
                    SqlHelper.ExecuteNonQuery(CommandType.Text, "EXEC SP_RENAME '[HOS_SALSRY_DETAIL].[" + strOldCode + "]','" + tbxFormTOTAL_ITEM_CODE.Text.Trim() + "'");
                    SqlHelper.ExecuteNonQuery(CommandType.Text, "EXEC SP_RENAME '[HOS_SALSRY_DETAIL_BAK].[" + strOldCode + "]','" + tbxFormTOTAL_ITEM_CODE.Text.Trim() + "'");
                    ShowNotify("保存成功!");
                }
                // 重新绑定表格，并点击当前编辑或者新增的行
                BindData();
                PageContext.RegisterStartupScript(Window1.GetHideReference());
            }
            catch (Exception ex)
            {

                throw new Exception("保存失败！");
            }

        }
    }
}